//
//  AppDelegate+Bugly.m
//  JSPatch
//
//  Created by yinli on 2018/1/13.
//  Copyright © 2018年 yinli. All rights reserved.
//

#import "AppDelegate+Bugly.h"

#import <BuglyHotfix/Bugly.h>
#import <BuglyHotfix/BuglyMender.h>
#import <JSPatch/JPEngine.h>

#import "QuickRSA.h"

@implementation AppDelegate (Bugly)

-(void)configBuglySDK {
    //初始化 Bugly 异常上报
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.delegate = self;
    config.debugMode = YES;
    config.reportLogLevel = BuglyLogLevelInfo;
    [Bugly startWithAppId:@"ee6d924c40"
#if DEBUG
        developmentDevice:YES
#endif
                   config:config];
    [self configJSPatchRequest];
}

- (void)configJSPatchRequest {
    //捕获 JSPatch 异常并上报
    [JPEngine handleException:^(NSString *msg) {
        NSException *jspatchException = [NSException exceptionWithName:@"Hotfix Exception" reason:msg userInfo:nil];
        NSLog(@"\njspatchException : %@",jspatchException);
        [Bugly reportException:jspatchException];
    }];
    //检测补丁策略
    [[BuglyMender sharedMender] checkRemoteConfigWithEventHandler:^(BuglyHotfixEvent event, NSDictionary *patchInfo) {
        //有新补丁或本地补丁状态正常
        if (event == BuglyHotfixEventPatchValid || event == BuglyHotfixEventNewPatch) {
            //获取本地补丁路径
            NSString *patchDirectory = [[BuglyMender sharedMender] patchDirectory];
            if (patchDirectory) {
                //指定执行的 js 脚本文件名
                NSString *patchFileName = @"main.js";
                NSString *patchFile = [patchDirectory stringByAppendingPathComponent:patchFileName];
                //执行补丁加载并上报激活状态
                if ([JPEngine evaluateScript:[self stringWithOpenSSLPEMEncFile:patchFile]] != nil) {
                    BLYLogInfo(@"evaluateScript success");
                    [[BuglyMender sharedMender] reportPatchStatus:BuglyHotfixPatchStatusActiveSucess];
                }else {
                    BLYLogInfo(@"evaluateScript failed");
                    [[BuglyMender sharedMender] reportPatchStatus:BuglyHotfixPatchStatusActiveFail];
                }
            }
        }
    }];
}

- (BOOL)canOpenSSLPEMEncFile:(NSString *)filePath {
    return [self encryptFile:filePath];
}

- (NSString *)stringWithOpenSSLPEMEncFile:(NSString *)filePath {
    NSData *decryptData = [self encryptFile:filePath];
    if (decryptData) {
        NSString *decryptStr = [[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding];
        return decryptStr.length > 0 ? decryptStr : nil;
    }
    return nil;
}

- (NSData *)encryptFile:(NSString *)filePath {
    NSString *public_key_pem = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzmnCuZCawbQtb2sSpCsknHFviG78GsBDcaV7MjKmOUFBRVL2rC1iKWE4vJD5GOlbYrL6k7FYQ2OzA4+e0PkRpxrGvFWfw2nAQThJIoewKz/xKBE8czcixLGtyoIVHjvIYP/B5EyfvVA8ozAAh8C2Wwv00VmCTK4L06CHDwzmyzQIDAQAB\n-----END PUBLIC KEY-----";
    NSData *keyData = [public_key_pem dataUsingEncoding:NSUTF8StringEncoding];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSData *encryptData = [NSData dataWithContentsOfFile:filePath];
        NSData *decryptData = [encryptData OpenSSL_RSA_DecryptDataWithPEM:keyData isPublic:YES];
        NSLog(@"\nENC succ \nfileContent: %@",[[NSString alloc] initWithData:decryptData encoding:NSUTF8StringEncoding]);
        return decryptData;
    }
    return nil;
}

@end
